package com.topway.dsmflex.model.synchro;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.topway.dsmflex.Log;
import com.topway.dsmflex.services.synchro.FileServices;
import com.topway.dsmflex.util.XmlEditUtil;





/**
 * 
 * @author liusy 2013-06-28
 *
 */
public class DataFileBean  extends DataTableBean{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private static Logger log = Logger.getLogger(DataFileBean.class);

	public DataFileBean()
	{
	}
	
	
	public DataFileBean(String tableNameTarget)
	{
		this.tableNameTarget =tableNameTarget;
	}
	
	/**
	 * 源文件路径
	 */
	private String sourceFilePath;
	/**
	 * 操作后源文件处理（不处理，删除，保存sourceFileSavePath）
	 */
	private String operatorSource;
	/**
	 * 源文件操作后保存目录
	 */
	private String sourceFileSavePath;
	/**
	 * 目标数据源
	 */
	private DataSourceBean targetDataSource;
	/**
	 * 目标数据源
	 */
	private String dsTarget;
	/**
	 * 目标表名
	 */
	private String tableNameTarget;
	/**
	 * 目标操作(INSERT,UPDATE,INSERTUPDATE,DELETE)
	 */
	private String operatorTarget;
	/**
	 * 列
	 */
	protected List<DataColumnBean> dataColumnBean;
	
	/**
	 * 文件类型，xls,txt
	 */
	private String fileType;
	/**
	 * 分隔符
	 */
	private String separate;
	/**
	 * 数据开始行
	 */
	private String startRow;
	
	
	
	
	
	public String getFileType() {
		return fileType;
	}
	public void setFileType(String fileType) {
		this.fileType = fileType;
	}
	public String getOperatorSource() {
		return operatorSource;
	}
	public void setOperatorSource(String operatorSource) {
		this.operatorSource = operatorSource;
	}
	public String getSourceFileSavePath() {
		return sourceFileSavePath;
	}
	public void setSourceFileSavePath(String sourceFileSavePath) {
		this.sourceFileSavePath = sourceFileSavePath;
	}
	public String getSeparate() {
		return separate;
	}
	public void setSeparate(String separate) {
		this.separate = separate;
	}
	public String getStartRow() {
		return startRow;
	}
	public void setStartRow(String startRow) {
		this.startRow = startRow;
	}
	public String getDsTarget() {
		return dsTarget;
	}
	
	
	
	
	public void setDsTarget(String dsTarget) {
		if(null==this.dsTarget&&!dsTarget.equals("")||(!dsTarget.equals("")&&!this.dsTarget.equals(dsTarget)))
		{
			this.dsTarget = dsTarget;
			try {
				this.targetDataSource = XmlEditUtil.getDataSourceByName(dsTarget);
			} catch (Exception e) {
				Log.error("["+this.getName()+"]该表不能运行   目标数据源["+dsTarget+"]不存在");
			}
		}
		checkDataSource();
	}
	
	


	/**
	 * 插入目标表数据sql
	 */
	private String insertTargetSql;
	/**
	 * 插入目标表数据sql
	 */
	private String updateTargetSql;
	
	/**
	 * 删除目标表数据sql
	 */
	private String deleteTargetSql;
	
	/**
	 * 根据源表Key条件查询目标表的数据sql
	 */
	private String selectTargetSql;
	
	
	/** 
	 * 对目标操作后执行sql
	 */
	protected String targetExecuteSql;
	
	
	
	/** 
	 * 同步数据同时执行目标库，使用{列}，当变量
	 */
	protected String currentTargetSql;
	/** 
	 * 同步数据同时执行目源库， 使用{列}，当变量
	 */ 
	protected String currentSourceSql;

	protected String pagingSql = "SELECT * FROM ( SELECT SHOWDATA.*, ROWNUM RN FROM ( #jobsql ) SHOWDATA ) WHERE RN <= #rownum_to AND RN > #rownum_from";
	
	protected int pageSize = 30000;
	
	protected int pageIndex = 0;
	
//	public String selectSourceNextPage(){
//		pageIndex++;
//		int rownfrom = (pageIndex-1)*pageSize;
//		int rownumto = pageIndex*pageSize;
//		return pagingSql.replace("#jobsql", this.selectSourceSql).replace("#rownum_from", ""+rownfrom).replace("#rownum_to", ""+rownumto);
//	}
	
	
	private boolean isRun = false;

	public boolean isRun() {
		return isRun;
	}
	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}
	
	
	
	
	public String getPagingSql() {
		return pagingSql;
	}
	public void setPagingSql(String pagingSql) {
		this.pagingSql = pagingSql;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getPageIndex() {
		return pageIndex;
	}
	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public DataSourceBean getTargetDataSource() {
		return targetDataSource;
	}
	public void setTargetDataSource(DataSourceBean targetDataSource) {
		this.targetDataSource = targetDataSource;
	}
	public String getSelectTargetSql() {
		return selectTargetSql;
	}
	public void setSelectTargetSql(String selectTargetSql) {
		this.selectTargetSql = selectTargetSql;
	}
	public String getUpdateTargetSql() {
		return updateTargetSql;
	}
	public void setUpdateTargetSql(String updateTargetSql) {
		this.updateTargetSql = updateTargetSql;
	}
	public String getTableNameTarget() {
		return tableNameTarget;
	}
	public void setTableNameTarget(String tableNameTarget) {
		this.tableNameTarget = tableNameTarget;
	}
	public String getOperatorTarget() {
		return operatorTarget;
	}
	public void setOperatorTarget(String operatorTarget) {
		this.operatorTarget = operatorTarget;
	}
	
	public List<DataColumnBean> getDataColumnBean() {
		return dataColumnBean;
	}
	public void setDataColumnBean(List<DataColumnBean> dataColumnBean) {
		this.dataColumnBean = dataColumnBean;
	}
	

	public String getInsertTargetSql() {
		return insertTargetSql;
	}
	public void setInsertTargetSql(String insertTargetSql) {
		this.insertTargetSql = insertTargetSql;
	}
	
	
	public String getTargetExecuteSql() {
		return targetExecuteSql;
	}
	public void setTargetExecuteSql(String targetExecuteSql) {
		this.targetExecuteSql = targetExecuteSql;
	}
	public String getDeleteTargetSql() {
		return deleteTargetSql;
	}
	public void setDeleteTargetSql(String deleteTargetSql) {
		this.deleteTargetSql = deleteTargetSql;
	}

	
	
	public String getCurrentTargetSql() {
		return currentTargetSql;
	}
	public void setCurrentTargetSql(String currentTargetSql) {
		this.currentTargetSql = currentTargetSql;
	}
	public String getCurrentSourceSql() {
		return currentSourceSql;
	}
	public void setCurrentSourceSql(String currentSourceSql) {
		this.currentSourceSql = currentSourceSql;
	}


	private List<String> columnSource = new ArrayList<String>();
	private List<String> columnTarget = new ArrayList<String>();
	private List<String> columnTargetValue = new ArrayList<String>();
	private List<String> keySource = new ArrayList<String>();
	private List<String> keyTarget = new ArrayList<String>();
	private List<String> keyTargetValue = new ArrayList<String>();
	private List<String> columnSourceUpdate = new ArrayList<String>();
	private List<String> columnTargetUpdate = new ArrayList<String>();
	private List<String> columnTargetUpdateValue = new ArrayList<String>();
	private List<String> colSourceUpdState = new ArrayList<String>();
	private List<String> colSourceUpdStateV = new ArrayList<String>();
	private Map<String,String> mapColExpress = new HashMap<String,String>();
	
	
	
	
	
	
	public Map<String, String> getMapColExpress() {
		return mapColExpress;
	}
	public void setMapColExpress(Map<String, String> mapColExpress) {
		this.mapColExpress = mapColExpress;
	}
	public List<String> getColumnSource() {
		return columnSource;
	}
	public void setColumnSource(List<String> columnSource) {
		this.columnSource = columnSource;
	}
	public List<String> getColumnTarget() {
		return columnTarget;
	}
	public void setColumnTarget(List<String> columnTarget) {
		this.columnTarget = columnTarget;
	}
	public List<String> getColumnTargetValue() {
		return columnTargetValue;
	}
	public void setColumnTargetValue(List<String> columnTargetValue) {
		this.columnTargetValue = columnTargetValue;
	}
	public List<String> getKeySource() {
		return keySource;
	}
	public void setKeySource(List<String> keySource) {
		this.keySource = keySource;
	}
	public List<String> getKeyTarget() {
		return keyTarget;
	}
	public void setKeyTarget(List<String> keyTarget) {
		this.keyTarget = keyTarget;
	}
	public List<String> getKeyTargetValue() {
		return keyTargetValue;
	}
	public void setKeyTargetValue(List<String> keyTargetValue) {
		this.keyTargetValue = keyTargetValue;
	}
	public List<String> getColumnSourceUpdate() {
		return columnSourceUpdate;
	}
	public void setColumnSourceUpdate(List<String> columnSourceUpdate) {
		this.columnSourceUpdate = columnSourceUpdate;
	}
	public List<String> getColumnTargetUpdate() {
		return columnTargetUpdate;
	}
	public void setColumnTargetUpdate(List<String> columnTargetUpdate) {
		this.columnTargetUpdate = columnTargetUpdate;
	}
	public List<String> getColumnTargetUpdateValue() {
		return columnTargetUpdateValue;
	}
	public void setColumnTargetUpdateValue(List<String> columnTargetUpdateValue) {
		this.columnTargetUpdateValue = columnTargetUpdateValue;
	}
	public List<String> getColSourceUpdState() {
		return colSourceUpdState;
	}
	public void setColSourceUpdState(List<String> colSourceUpdState) {
		this.colSourceUpdState = colSourceUpdState;
	}
	public List<String> getColSourceUpdStateV() {
		return colSourceUpdStateV;
	}
	public void setColSourceUpdStateV(List<String> colSourceUpdStateV) {
		this.colSourceUpdStateV = colSourceUpdStateV;
	}
	
	
	
	
	
	
	public void Run() {
		try {
			if(this.enabled!=1)
				return;
				
			
			if(null==operatorTarget || operatorTarget.equals("") ||operatorTarget.equals("NO") )
			{
				this.setRun(false);
				return ;
			}
			if(null==dataColumnBean || dataColumnBean.size()==0)
			{
				this.setDataColumnBean(FileServices.getFileServices().getColumnInfo(this));
			}
			
			if(null!=dataColumnBean && dataColumnBean.size()>0)
			{
			this.setRun(true);
			
		
			columnSource.clear();
			columnTarget.clear();
			columnTargetValue.clear();
			keySource.clear();
			keyTarget.clear();
			keyTargetValue.clear();
			columnSourceUpdate.clear();
			columnTargetUpdate.clear();
			columnTargetUpdateValue.clear();
			colSourceUpdState.clear();
			colSourceUpdStateV.clear();
			mapColExpress.clear();
			
			//对源表删除、更新、查询的条件
			StringBuilder selectSourceWhere = new StringBuilder();
			StringBuilder columnTargetUpdatStr = new StringBuilder();
			StringBuilder colSourceUpdStateStr = new StringBuilder();
			
			StringBuilder keyWehre = new StringBuilder(" 1=1  AND ");
			
			
			String _selectSourceWhere = "";
			DataColumnBean dc;
			for (int i = 0; i < dataColumnBean.size(); i++) {
				dc = dataColumnBean.get(i);
				if(null!=dc.getColumnNameSource()&& !dc.getColumnNameSource().equals("")
						&& null!=dc.getColumnNameTarget() &&!dc.getColumnNameTarget().equals(""))
				{
					//columnSource.add(dc.getColumnNameSource());
					columnSource.add(""+i);
					columnTargetValue.add("?");
					if(columnTarget.contains(dc.getColumnNameTarget()))
					{
						columnTarget.add(dc.getColumnNameTarget());
						setRun(false);
						Log.error("请检查表["+this.getName()+"]的目标列是否重复");
						break;
					}
					columnTarget.add(dc.getColumnNameTarget());
				}
				if(null!=dc.getIsKey()&& dc.getIsKey().equals("YES") && null!=dc.getColumnNameTarget() && !dc.getColumnNameTarget().equals(""))
				{
				//	keySource.add(dc.getColumnNameSource());
					keySource.add(""+i);
					keyTarget.add(dc.getColumnNameTarget());
					keyTargetValue.add("?");
					keyWehre.append(dc.getColumnNameTarget()).append("=").append("?").append(" AND ");
				}
				else if(null!=dc.getColumnNameTarget() && !dc.getColumnNameTarget().equals(""))
				{
					//columnSourceUpdate.add(dc.getColumnNameSource());
					columnSourceUpdate.add(""+i);
					columnTargetUpdate.add(dc.getColumnNameTarget());
					columnTargetUpdateValue.add("?");
					columnTargetUpdatStr.append(dc.getColumnNameTarget()).append("=?, ");
				}
				if(null != dc.getColExpress()&& !dc.getColExpress().equals(""))
				{
					//mapColExpress.put(dc.getColumnNameSource(), dc.getColExpress());
					mapColExpress.put(""+i, dc.getColExpress());
				}
			}
			
			String where =  selectSourceWhere+_selectSourceWhere;
			if(where.length()>0)
			{
				where="  where "+where;
			}



			String _insertTargetSql = "";
			try {
				_insertTargetSql = "insert into "+this.getTableNameTarget()+"("+ListConvertString(columnTarget)+") values("+ListConvertString(columnTargetValue)+")";;
			} catch (Exception e) {
				Log.warning(e.getMessage()+"_insertTargetSql 错误!");
			}
			String _updateTargetSql = "";
			try {
				_updateTargetSql = "update  "+this.getTableNameTarget()+" set "+columnTargetUpdatStr.substring(0,columnTargetUpdatStr.length()-2)+" where "+keyWehre.substring(0, keyWehre.length()-5);
			} catch (Exception e) {
				Log.warning(e.getMessage()+"_updateTargetSql 错误!");
			}
			String _deleteTargetSql = "";
			try {
				_deleteTargetSql = "delete  "+this.getTableNameTarget()+" where "+keyWehre.substring(0, keyWehre.length()-5);
			} catch (Exception e) {
				Log.warning(e.getMessage()+"_deleteTargetSql 错误!");
			}
			String _selectTargetSql = "";
			try {
				_selectTargetSql = "select "+ListConvertString(columnTarget)+" from "+this.getTableNameTarget() +" where "+keyWehre.substring(0, keyWehre.length()-5);
			} catch (Exception e) {
				Log.warning(e.getMessage()+"_selectTargetSql 错误!");
			}

			
			
			
				if(!_insertTargetSql.equals(""))
				this.setInsertTargetSql(_insertTargetSql);
				if(!_updateTargetSql.equals("")) 
				this.setUpdateTargetSql(_updateTargetSql);
				if(!_selectTargetSql.equals(""))
				this.setSelectTargetSql(_selectTargetSql);
				if(!_deleteTargetSql.equals(""))
				this.setDeleteTargetSql(_deleteTargetSql);
				
				if(null==this.sourceFilePath||this.sourceFilePath.equals(""))
				{
					Log.error("原文件文件目录不存在！！任务［"+this.getName()+"］");
					isRun = false;
					return;
				}
				
				if(!new File(this.sourceFilePath).exists()){
					Log.error("文件目录不存在！！任务［"+this.getName()+"］中文件［"+sourceFilePath+"］");
					isRun = false;
					return;
				}
				
				
			if(!this.isRun)
			{
				Log.error("["+this.getName()+"]该任务不能运行");
				Log.error("请检查任务["+this.getName()+"]是否配置正确！");
				Log.error(columnTarget.toString());
				this.setRun(false);
				return ;
			}

			if(null!=operatorTarget&&this.operatorTarget.contains("UPDATE") && _updateTargetSql.equals(""))
			{
				Log.error("源["+this.getName()+"]对目标表["+this.getTableNameTarget()+"]不能执行更新操作");
				Log.error("请检查主键条件设置是否正确");
				this.setRun(false);
			}
			if(null!=operatorTarget&&this.operatorTarget.contains("DELETE") && _updateTargetSql.equals(""))
			{
				Log.error("源["+this.getName()+"]对目标表["+this.getTableNameTarget()+"]不能执行删除操作");
				Log.error("请检查主键条件设置是否正确");
				this.setRun(false);
			}
			if(null!=operatorTarget&&this.operatorTarget.contains("INSERT") && _insertTargetSql.equals(""))
			{
				Log.error("源["+this.getName()+"]对目标表["+this.getTableNameTarget()+"]不能执行新增操作");
				Log.error("请添加源表字段与目标表对应的字段");
				this.setRun(false);
			}
			
			checkDataSource();
			}
		} catch (Exception e) {
			this.setRun(false);
			e.printStackTrace();
		}finally{
			if(this.enabled==1)
			if(!this.isRun)
			{
				Log.error("源["+this.getName()+"]不能运行，配置未能通过验证!");
			}
		}
		
	}
	
	
	private boolean checkDataSource()
	{
		if(null==dsTarget||dsTarget.equals("")|| null==targetDataSource)
		{
			Log.error("["+this.getName()+"]该表不能运行   [目标数据源]、或者[源数据源]不存在");
			this.setRun(false);
		}
		else if(!dsTarget.equals(this.targetDataSource.getDataSourceName()))
		{
			try {
				this.targetDataSource = XmlEditUtil.getDataSourceByName(dsTarget);
			} catch (Exception e) {
				Log.error("["+this.getName()+"]该表不能运行   目标数据源["+dsTarget+"]不存在");
			}
			if(null==dsTarget)
			{
				Log.error("["+this.getName()+"]该表不能运行    目标数据源["+dsTarget+"]不存在");
			}
		}
		return this.isRun;
	}
	
	

	/**
	 * 
	 * @param [a,b,d]
	 * @return a,b,c,d
	 */
	public String ListConvertString(List<String> list)
	{
		if(null==list ||list.size()==0)
			return "";
		String str = Arrays.toString(list.toArray());
		return str.substring(1, str.length()-1);
	}
	
	
	
	


	
	
	
	
	
	
	public Map<String,String> mapColumnValue = new HashMap<String,String>();
	
	public Map<String,String> maStatisValue = new HashMap<String,String>();
	
	public Map<String, String> getMapColumnValue() {
		return mapColumnValue;
	}
	public void setMapColumnValue(Map<String, String> mapColumnValue) {
		this.mapColumnValue = mapColumnValue;
	}
	public Map<String, String> getMaStatisValue() {
		return maStatisValue;
	}
	public void setMaStatisValue(Map<String, String> maStatisValue) {
		this.maStatisValue = maStatisValue;
	}
	
	
	public String getSourceFilePath() {
		return sourceFilePath;
	}
	public void setSourceFilePath(String sourceFilePath) {
		this.sourceFilePath = sourceFilePath;
	}
	
	
	
	
	
	public String getTableNameSource()
	{
		return this.getName();
	}
	
	
	
	
	
	
	
	
	public static void main(String[] args) {
		int count=1;
		for(int i=0;i<10;i++)
		{
			count=(count*2)+1;

		}
		System.out.println(count);
		
		
		int count1=2048;
		for(int i=0;i<10;i++)
		{
			count1=(count1/2)-1;

		}
		System.out.println(count1);
	}

	
}
